//app.js
const hosts = 'https://yangjifang.yuanbaohua.top';
App({
  onLaunch: function () {
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    this.globalData.hosts = hosts;
    wx.setStorageSync('company_type', '-1'); //初始打开为普通用户状态

  },
  onShow:function(){
    let that = this;
    this.login();
  },
  login:function(){
    let that = this;
    //console.log("开始登陆");
    wx.login({
      success: function (res) {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        //console.log(res.code);
        wx.request({
          url: hosts + '/index/wxlogin/login',
          data: { code: res.code },
          method: 'POST',
          header: {
            "X-Requested-With": 'XMLHttpRequest'
          },
          success: function (res) {
            let token = res.data.msg;
            that.globalData.token = token;

            wx.setStorageSync("login_token", res.data.msg);
            wx.getSetting({
              success: function (res) {
                if (res.authSetting['scope.userInfo']) {
                  that.globalData.isAuth = true;
                  // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                  wx.getUserInfo({
                    success: function (res) {

                      // 可以将 res 发送给后台解码出 unionId
                      that.globalData.userInfo = res.userInfo;
                      that.globalData.token = token;
                      //console.log({ userInfo: res.userInfo });
                      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                      // 所以此处加入 callback 以防止这种情况
                      wx.request({
                        url: hosts + '/index/login/updateUserInfo',
                        data: res.userInfo,
                        method: 'POST',
                        header: {
                          'X-Requested-With': 'XMLHttpRequest',
                          "Authentication": token
                        },
                        success: function (res) {
                          //console.log(res);
                        }
                      });
                    },
                  });
                }
              }
            });

           
            if (that.userInfoReadyCallback) {
              that.userInfoReadyCallback(res);
            }

          },

        });
        
      }
    });
  },

  globalData: {
    userInfo: null,
    isAuth:false,
  }
})